﻿using PMS.Core.Configuration.CommonEnumConfigs;
using PMS.Core.Utils;
using PMS.Services.EntityServices.Messages;
using PMS.Services.Utils.Messages;
using System;

namespace PMS.Services.Utils.ScheduleTasks
{
    /// <summary>
    /// Represents a task for sending queued message 
    /// </summary>
    public partial class QueuedMessagesSendTask : IScheduleTask
    {
        #region Fields

        private readonly IEmailAccountService _emailAccountService;
        private readonly IEmailSender _emailSender;
        private readonly IQueuedEmailService _queuedEmailService;

        #endregion

        #region Ctor

        public QueuedMessagesSendTask(IEmailAccountService emailAccountService,
            IEmailSender emailSender,
            IQueuedEmailService queuedEmailService)
        {
            _emailAccountService = emailAccountService;
            _emailSender = emailSender;
            _queuedEmailService = queuedEmailService;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Executes a task
        /// </summary>
        public virtual bool Execute()
        {
            var maxTries = 3;
            //阿里云邮件推送服务免费量为每天推送200封
            //故配合TaskManager计划任务每天运行一次，每次发送200
            //后期根据项目实际需要可修改计划任务执行频率及每次发送数量
            int maxSendEmails = 200; 
            var queuedEmails = _queuedEmailService.SearchEmails(null, null, null, null,
                true, true, maxTries, false, 0, maxSendEmails); 
            foreach (var queuedEmail in queuedEmails)
            {
                var bcc = _queuedEmailService.ConvertDelimtedString(queuedEmail.Bcc);
                var cc = _queuedEmailService.ConvertDelimtedString(queuedEmail.CC);

                try
                {
                    _emailSender.SendEmail(_emailAccountService.GetEmailAccountById(queuedEmail.EmailAccountId),
                        queuedEmail.Subject,
                        queuedEmail.Body,
                        queuedEmail.From,
                        queuedEmail.FromName,
                        queuedEmail.To,
                        queuedEmail.ToName,
                        queuedEmail.ReplyTo,
                        queuedEmail.ReplyToName,
                        bcc,
                        cc,
                        queuedEmail.AttachmentFilePath,
                        queuedEmail.AttachmentFileName);

                    queuedEmail.SentOnTimeUtc = DateTime.UtcNow;
                }
                catch (Exception exc)
                {
                    //_logger.Error($"Error sending e-mail. {exc.Message}", exc);
                    //Catch Exceptions Handled by ProcessTask
                    throw new PMSException($"Error sending e-mail. {exc.Message}", SystemLogLevel.Error);
                }
                finally
                {
                    queuedEmail.SentTries += 1;
                    queuedEmail.IsActive = false;
                    _queuedEmailService.UpdateQueuedEmail(queuedEmail);
                }
            }
            return true;
        }

        #endregion
    }
}
